package org.example.tool;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.collections4.CollectionUtils;
import org.example.area.AreaDto;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author sunshuai
 * @date 2022/3/31 15:47
 * @description: word生成工具
 */
public class WordUtils {
    public static void saveWord(String filePath, Map<String,Object> dataMap,String templateName) {
        InputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");
            configuration.setClassForTemplateLoading(WordUtils.class, "/");
            Template template = configuration.getTemplate("inspectionReportV2".equals(templateName) ? "templates/inspectionReportV2.ftl" : "templates/inspectionSurveyV2.ftl");
            InputStreamSource streamSource = createWord(template, dataMap);
            inputStream = streamSource.getInputStream();
            outputStream = new FileOutputStream(filePath);
            byte[] bytes = new byte[1024];
            while ((inputStream.read(bytes)) != -1) {
                outputStream.write(bytes);// 写入数据
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static InputStreamSource createWord(Template template, Map<String, Object> dataMap) {
        StringWriter out = null;
        Writer writer = null;
        try {
            out = new StringWriter();
            writer = new BufferedWriter(out, 1024);
            template.process(dataMap, writer);
            return new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static Map<String, Object> transferParam(String tbzzz,String tbzw,String cydd,List<Map<String, Object>> inspectionReportList){
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("name", fillSpace(tbzzz,29));
        dataMap.put("tbzw", tbzw);
        dataMap.put("cydd", cydd);
        dataMap.put("cysj", DateUtils.dateFormat(new Date()));
        List<Map<String, Object>> lists = new ArrayList<>();
        int size = inspectionReportList.size();
        if(size>20){
            int page = size%20==0?size/20:size/20+1;
            for(int i=0;i<page;i++){
                Map<String, Object> pageData = new HashMap<>();
                int limit = (i==page-1&&size%20!=0)?size%20:20;
                List<Map<String, Object>> subList = inspectionReportList.subList(i * 20, i * 20 + limit);
                pageData.put("zmj",calculateArea(subList));
                pageData.put("pageData",fillBlankData(subList));
                lists.add(pageData);
            }
        }else{
            Map<String, Object> pageData = new HashMap<>();
            pageData.put("zmj",calculateArea(inspectionReportList));
            pageData.put("pageData",fillBlankData(inspectionReportList));
            lists.add(pageData);
        }
        dataMap.put("list", lists);
        return dataMap;
    }
    //计算总投保面积
    private static double calculateArea(List<Map<String, Object>> data){
        double zmj = 0;
        if(!CollectionUtils.isEmpty(data)){
            for(Map<String,Object> map:data){
                double tbmj = Double.parseDouble(map.get("tbmj").toString());
                zmj+=tbmj;
            }
        }
        return zmj;
    }
    //填充id和不足20行的空白行
    private static List<Map<String, Object>> fillBlankData(List<Map<String, Object>> inspectionReportList){
        List<Map<String, Object>> result = new ArrayList<>();

        for(int y=1;y<=inspectionReportList.size();y++){
            Map<String, Object> map = new HashMap();
            Map<String, Object> old = inspectionReportList.get(y - 1);
            map.put("sffh",old.get("sffh"));
            map.put("tbdh",old.get("tbdh"));
            map.put("bz",old.get("bz"));
            map.put("nhxm",old.get("nhxm"));
            map.put("tbmj",old.get("tbmj"));
            map.put("id",y);
            result.add(map);
        }
        if(inspectionReportList.size()<20){
            for(int z = inspectionReportList.size()+1;z<=20;z++){
                Map<String, Object> padding = new HashMap<>();
                padding.put("id",z);
                padding.put("nhxm", "");
                padding.put("tbdh","");
                padding.put("tbmj","");
                padding.put("sffh", "");
                padding.put("bz", "");
                result.add(padding);
            }
        }
        return result;
    }

    //填充空格，使右侧文字可以右对齐，不换行
    private static String fillSpace(String str,int totalLength){
        StringBuilder sb = new StringBuilder(str);
        int length = str.length();
        if(totalLength>length){
            int count = totalLength - length;
            for(int i = 0;i<count;i++){
                sb.append("&#160;");
            }
        }
        return sb.toString();
    }

    public static Map<String, Object> transferInspectionReportParam(String tbzzz,String tbdh,String tbr,String tbzw,String cydd,int zltCount,int cyqdPage,int farmerCount){
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("tbzzz", Objects.isNull(tbzzz)?"":tbzzz);
        dataMap.put("tbdh", Objects.isNull(tbdh)?"":tbdh);
        dataMap.put("tbr", Objects.isNull(tbr)?"":tbr);
        dataMap.put("tbzw", Objects.isNull(tbzw)?"":tbzw);
        dataMap.put("bzpz", fillSpace(Objects.isNull(tbzw)?"":tbzw,18));
        dataMap.put("cydd", Objects.isNull(cydd)?"":cydd);
        dataMap.put("zltCount", zltCount);
//        dataMap.put("cyrq", Objects.isNull(cyrq)?"":cyrq);
        dataMap.put("cyqdPage", cyqdPage);
        dataMap.put("farmerCount", farmerCount);
        return dataMap;
    }

    private static void generateWord(String path, AreaDto area, List<Map<String, Object>> inspectionReportList, String groupName, String tbdh, String tbr, int zltCount){
        int farmerCount = inspectionReportList.size();
        String inspectionSurveyWordFileName = "种植业保险标的查验调查表.docx";
        Map<String, Object> wordParam = WordUtils.transferParam(area.getCountyName() + area.getTownName() + area.getVillageName(), groupName, area.getVillageName(), inspectionReportList);
        WordUtils.saveWord(path+ File.separator + inspectionSurveyWordFileName,wordParam ,"inspectionSurveyV2");
        List lists = (List) wordParam.get("list");
        Map<String, Object> inspectionReportParam = WordUtils.transferInspectionReportParam(area.getCountyName() + area.getTownName() + area.getVillageName(), tbdh, tbr, groupName, area.getVillageName(), zltCount,  lists.size(), farmerCount);
        String inspectionReportWordFileName = "种植业保险查验报告单.docx";
        WordUtils.saveWord(path+ File.separator + inspectionReportWordFileName, inspectionReportParam,"inspectionReportV2");
    }
    public static void main(String[] args){
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("tbzzz", "sunshuai");
        dataMap.put("szqk", "正常");
        dataMap.put("tbdh", "tbdh001");
        dataMap.put("tbr", "shuai");
        dataMap.put("tbzw", "小麦");
        dataMap.put("cydd", "郑州村");
        dataMap.put("zltCount", "12");
        dataMap.put("cyrq", "2022年2月11日");
        WordUtils.saveWord("D:\\test2.docx", dataMap,"inspectionReport");
        AreaDto areaDto = new AreaDto();
        areaDto.setProvinceName("河南省");
        areaDto.setCityName("郑州市");
        areaDto.setCountyName("高新区");
        areaDto.setTownName("石佛镇石佛镇石佛镇");
        areaDto.setVillageName("海棠社区");
        List<Map<String, Object>> inspectionReportList=new ArrayList<>();
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("nhxm", "荷里活");
        map.put("tbdh","BDH001");
        map.put("tbmj","10.01");
        map.put("sffh", "是");
        map.put("bz", "");
        inspectionReportList.add(map);
        generateWord("D:\\",areaDto,inspectionReportList,"玉米玉米玉米","TBDH001","荷里活",10);
//        int size=80;
//        int page = size%20==0?size/20:size/20+1;
//        for(int i=0;i<page;i++){
//            Map<String, Object> pageData = new HashMap<>();
//            int limit = (i==page-1&&size%20!=0)?size%20:20;
//            System.out.println(limit);
//        }

    }
//    public static void main(String[] args){
//        Map<String, Object> dataMap = new HashMap<>();
//        dataMap.put("name", "sunshuai");
//        dataMap.put("tbzw", "小麦");
//        dataMap.put("cydd", "郑州");
//        dataMap.put("cysj", "2022-03-31");
//        ArrayList<List<Map<String, Object>>> lists = new ArrayList<>();
//        List<Map<String, Object>> newsList=new ArrayList<Map<String,Object>>();
//
//        for(int i=1;i<=20;i++){
//            Map<String, Object> map=new HashMap<String, Object>();
//            map.put("id", i);
//            map.put("nhxm", "nhxm"+i);
//            map.put("tbdh", "tbdh"+i);
//            map.put("tbmj", "tbmj"+i);
//            map.put("sffh", "是");
//            map.put("bz", "");
//            newsList.add(map);
//        }
//        lists.add(newsList);
//        lists.add(newsList);
//        dataMap.put("list", lists);
//        WordUtils.saveWord("D:\\test.docx", dataMap,"inspectionSurvey");
//    }
}
